local cjson     = require "cjson"
local jwt       = require "resty.jwt"
local redis     = require "redis"
local utils     = require "utils"
local mysql     = require "resty.mysql"
local resty_md5 = require "resty.md5"
local keysutils = require "keysutils"
local http      = require "http"
local str       = require "resty.string"
local global    = require "global"

math.randomseed(tostring(os.time()):reverse():sub(1, 7))

local function concat_args(args, mark)
    local list = {}
    for k, v in pairs(args) do
        if v ~= '' then
            list[#list+1] = string.format(mark and '%s="%s"' or '%s=%s', k, v)
        end
    end
    assert(#list > 0, "need one arg at least")
    table.sort(list, function(a, b)
        return a < b
    end)
    return table.concat(list, "&")
end

ngx.header['Content-Type'] = 'application/json; charset=utf-8'

local headers = ngx.req.get_headers()

local nonce = headers["x-nonce-str"]
local timestamp = headers["x-timestamp"]
local signature = headers["x-signature"]
local roomid = headers["x-roomid"]
local msg_type = headers["x-msg-type"]
local content_type = headers["content-type"]

local arg = ngx.req.get_uri_args()

local body = ngx.req.get_body_data()
ngx.log(ngx.INFO,"body=======================>",body)
local ok, req_data = pcall(cjson.decode,body)
if not ok then
    ngx.say(cjson.encode({errcode=501, errmsg="系统繁忙", data={}}))
    return ngx.exit(501)
end

local args = {
    ["x-nonce-str"] = nonce,
    ["x-timestamp"] = timestamp,
    ["x-roomid"] = roomid,
    ["x-msg-type"] = msg_type
}

local md5_str = concat_args(args)

md5_str =  md5_str .. body .. DOUYIN_CONFIG.secret

local md5 = resty_md5:new()
md5:update(md5_str)
local digest = md5:final()
local digest_str = str.to_hex(digest)
local sign_str = ngx.encode_base64(digest_str)
print("sign_str = ", sign_str)
-- if sign_str ~= signature then
--     ngx.say(cjson.encode({errcode=401, errmsg="签名错误", data={}}))
--     return ngx.exit(401)
-- end

local sock = ngx.socket.tcp()
local ok, err = sock:connect(SKYNET_CONFIG.ip, SKYNET_CONFIG.port)

assert(ok, "failed to connect to skynet")

local cmd = {
    c = "room",
    m = "sendmsg",
    data = {
        roomid = roomid,
        msg_type = msg_type,
        msg = req_data
    }
}

local data = utils.msgpack(cmd)
local bytes, err = sock:send(data)

assert(err == nil, "failed to send to skynet")

sock:setkeepalive(60000, 100)

ngx.say(cjson.encode({ errcode = 0, errmsg = "回调成功", data = req_data }))

